package com.woniuxy.cloud.carl.order.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.cloud.Aspect.log.Log;
import com.woniuxy.cloud.carl.carlgoods.client.SkuQueryClient;
import com.woniuxy.cloud.carl.carlgoods.client.dto.SkuDto;
import com.woniuxy.cloud.carl.order.app.utils.OSSUtil;
import com.woniuxy.cloud.carl.order.app.utils.QrCodeUtil;
import com.woniuxy.cloud.carl.order.client.OrderManageClient;
import com.woniuxy.cloud.carl.order.client.ServiceQueryClient;
import com.woniuxy.cloud.carl.order.client.param.AddOneOrderParam;
import com.woniuxy.cloud.carl.order.client.param.AddOrderParam;
import com.woniuxy.cloud.carl.order.client.result.OrderDetailDto;
import com.woniuxy.cloud.carl.order.client.result.ServiceDetailDto;
import com.woniuxy.cloud.carl.order.common.CommonResultCode;
import com.woniuxy.cloud.carl.order.common.ConstantData;
import com.woniuxy.cloud.carl.order.common.OrderResultCode;
import com.woniuxy.cloud.carl.order.infra.model.*;

import com.woniuxy.cloud.carl.order.service.*;

import com.woniuxy.cloud.carl.user.client.UserManageClient;
import com.woniuxy.cloud.carl.user.client.UserQueryClient;
import com.woniuxy.exceptions.MallException;
import com.woniuxy.result.Result;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
@RestController
public class OrderManageApiImpl implements OrderManageClient {

    @Resource
    private OrderService orderService;
    @Resource
    private ServiceQueryApiImpl serviceQueryApi;

    @Resource
    private OrderItemService orderItemService;
    @Resource
    private ServiceOrderItemService serviceOrderItemService;

    @Resource
    private SkuQueryClient skuQueryClient;
    @Resource
    private SkuOrderItemService skuOrderItemService;
    @Resource
    private ServiceItemService serviceItemService;
    @Resource
    private OrderLogService orderLogService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private UserDeliveryService userDeliveryService;
    @Resource
    private UserQueryClient userQueryClient;
    @Resource
    private UserManageClient userManageClient;


    @GetMapping("test")
    public Result testMQ(){
        Order order = orderService.getById(6);
        Message<Order> message = MessageBuilder.withPayload(order).build();
//        rocketMQTemplate.syncSend("order_log",message);
//        rocketMQTemplate.syncSend("order_log",message,3000,4);
        return Result.success();
    }

    @Override
    @Log(value = "创建订单")
    @GlobalTransactional
    public Result<String> createOneOrder(AddOneOrderParam param) {
        //mainSite判断 userId、addressId、couponId、storeId、skuId、serviceId存在性

        //新增order
        Order order = BeanUtil.toBean(param, Order.class);
        String orderNum = new Snowflake().nextIdStr();
        order.setOrderNum(orderNum);
        order.setOrderStatus(ConstantData.ORDER_STATE_WAITE);
        order.setCreateTime(new Date());
        BigDecimal scoreB = param.getRealPay().divide(new BigDecimal(10));
        int score = scoreB.intValue();
        order.setGainScore(score);
        if(param.getCouponType()!=null){ //非积分兑换
            if(param.getCouponType()==0) {
                order.setCouponId(param.getCouponId());
                order.setCouponAmount(param.getCouponAmount());
            }
        }
        if(param.getCouponType()==null){ //积分兑换
            //优惠金额？
        }

        orderService.save(order);


        //新增服务orderItem
        if(param.getServiceId()!=null){

            ServiceDetailDto serviceDetailDto = serviceQueryApi.findServiceDetail(param.getServiceId()).getData();
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setCommentFlag(ConstantData.COMMENT_NOT);
            orderItem.setTypeFlag(ConstantData.SERVICE_ORDER);

            //价格
            orderItem.setOriginalPrice(param.getOriginalTotal()); //原价
            orderItem.setUserCouponId(param.getCouponId()); //优惠金额
            orderItem.setCouponPrice(param.getCouponAmount());
            orderItem.setItemTotalDiscountPrice(param.getDiscountAmount());//打折金额
            orderItem.setRealPay(param.getRealPay()); //实际支付
            orderItem.setImage(serviceDetailDto.getServiceImage());
            orderItem.setUserCouponId(param.getItemCouponId());
            orderItemService.save(orderItem);

            //新增服务条目详情表
            ServiceOrderItem serviceOrderItem = BeanUtil.toBean(serviceDetailDto, ServiceOrderItem.class);
            ServiceDetailDto detailDto = serviceQueryApi.findServiceDetail(param.getServiceId()).getData();
            serviceOrderItem.setStoreId(param.getStoreId());
            serviceOrderItem.setServiceStatus(ConstantData.SERVICE_NOT_USE);
            serviceOrderItem.setOrderItemId(orderItem.getOrderItemId());
            serviceOrderItem.setServiceName(detailDto.getServiceName());
            serviceOrderItemService.save(serviceOrderItem);

            //新增服务订单商品表
            if(serviceDetailDto.getSkuId()!=null){
                ServiceItem serviceItem = BeanUtil.toBean(serviceDetailDto, ServiceItem.class);
                serviceItem.setOrderItemId(orderItem.getOrderItemId());
                serviceItemService.save(serviceItem);
            }
        }
        //新增商品orderItem
        if(param.getSkuId()!=null){
            SkuDto skuDto = skuQueryClient.findSkuById(param.getSkuId()).getData();
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setCommentFlag(ConstantData.COMMENT_NOT);
            orderItem.setTypeFlag(ConstantData.SKU_ORDER);

            //价格
            orderItem.setOriginalPrice(param.getOriginalTotal()); //原价
            orderItem.setUserCouponId(param.getCouponId()); //优惠金额
            orderItem.setCouponPrice(param.getCouponAmount());
            orderItem.setItemTotalDiscountPrice(param.getDiscountAmount());//打折金额
            orderItem.setRealPay(param.getRealPay()); //实际支付
            orderItem.setOrderItemId(param.getItemCouponId());
            orderItem.setImage(skuDto.getImage());
            orderItemService.save(orderItem);


            //新增商品条目详情表
            SkuOrderItem skuOrderItem = new SkuOrderItem();
            skuOrderItem.setSkuId(param.getSkuId());
            skuOrderItem.setSkuCount(param.getCount());
            skuOrderItem.setOrderItemId(orderItem.getOrderItemId());
            skuOrderItem.setSkuName(skuDto.getSkuName());
//            skuOrderItem.setSkuName("标准洗车");
            skuOrderItem.setDeliveryStatus(ConstantData.EXPRESS_ING);
            skuOrderItemService.save(skuOrderItem);
        }
        //创建订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderNum(orderNum);
        orderLog.setContent("用户id为："+param.getUserId()+"创建订单");
        orderLog.setLogDate(new Date());
        orderLog.setOperator("系统自动");
        orderLogService.save(orderLog);




        return Result.success(order.getOrderNum());
    }

    @Override
    public Result createOrderByCart(AddOrderParam param) {

        return null;
    }

    @Override
    public Result cancelOrder(String orderNum,Long userId) {
        //前置判断 已送达不能取消、 服务已核销不能取消、 订单已完成不能取消
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_num", orderNum));
        if(userId!=order.getUserId()){ //用户不对头
            throw new MallException(OrderResultCode.ORDER_CAN_NOT_CANCEL);
        }
        OrderItem orderItem = orderItemService.getOne(new QueryWrapper<OrderItem>().eq("order_id", order.getOrderId()));
        if(order.getOrderStatus()==ConstantData.ORDER_STATE_FINISH){ //订单已完成
            throw new MallException(OrderResultCode.ORDER_CAN_NOT_CANCEL);
        }
        //服务已完成 或者已过期
        ServiceOrderItem serviceOrderItem = serviceOrderItemService.getOne(new QueryWrapper<ServiceOrderItem>().eq("order_item_id", orderItem.getOrderItemId()));
        if(serviceOrderItem.getServiceStatus()!=ConstantData.SERVICE_NOT_USE){ throw new MallException(OrderResultCode.ORDER_CAN_NOT_CANCEL);}

        //修改order表
        order.setOrderStatus(ConstantData.ORDER_STATE_CANCEL);
        orderService.saveOrUpdate(order);
        //创建日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderNum(orderNum);
        orderLog.setLogDate(new Date());
        orderLog.setContent("取消订单");
        orderLog.setOperator("用户："+order.getUserId());
        orderLogService.save(orderLog);
        return Result.success(CommonResultCode.CANCEL_ORDER_SUCCESS);
    }

    @Override
    public Result payOrder(String num) { //订单支付中
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_num", num));
        order.setOrderStatus(ConstantData.ORDER_STATE_PAYING);
        return Result.success();
    }

    @Autowired
    OSSUtil ossUtil;
    @Override
    public Result payCallback(String num) {  //支付完成
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_num", num));
        if (order.getOrderStatus()==0){
            order.setOrderStatus(ConstantData.ORDER_STATE_PAYED);
            order.setPaymentTime(new Date());
            order.setPayMethod(1);  //支付宝支付
            orderService.saveOrUpdate(order);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderNum(num);
            orderLog.setContent("订单已支付");
            orderLog.setLogDate(new Date());
            orderLog.setOperator("用户："+order.getUserId());
            orderLogService.save(orderLog);
        }
        return Result.success();
    }

    @Override
    public Result setCommentFlag(Long orderItemId) {
        OrderItem orderItem = orderItemService.getById(orderItemId);
        orderItem.setCommentFlag(ConstantData.COMMENT_ED);
        orderItemService.saveOrUpdate(orderItem);
        return Result.success();
    }

    @Override
    public Result useCode(Long orderItemId) {
        //改serviceOrderItem表
        ServiceOrderItem one = serviceOrderItemService.getOne(new QueryWrapper<ServiceOrderItem>().eq("order_item_id", orderItemId));
        one.setServiceStatus(ConstantData.SERVICE_USED);
        serviceOrderItemService.saveOrUpdate(one);
        OrderItem orderItem = orderItemService.getById(orderItemId);
        //改order表
        Order order = orderService.getById(orderItem.getOrderId());
        order.setOrderStatus(ConstantData.ORDER_STATE_FINISH);
        orderService.saveOrUpdate(order);
        //新增orderLog日志表
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderNum(order.getOrderNum());
        orderLog.setLogDate(new Date());
        orderLog.setOperator("用户："+order.getUserId());
        orderLog.setContent("服务订单已核销");
        orderLogService.save(orderLog);
        return Result.success();
    }

    @Override
    public Result receive(Long deliveryId) {
        UserDelivery userDelivery = userDeliveryService.getById(deliveryId);
        //改用户物流表
        if(userDelivery==null) { throw new MallException(OrderResultCode.EXPRESS_NOT_EXIST);}
        if(userDelivery.getDeliveryStatus()!=ConstantData.EXPRESS_ING) {throw new MallException(OrderResultCode.EXPRESS_IS_RECEIVE);}
        userDelivery.setDeliveryStatus(ConstantData.EXPRESS_ED);
        userDeliveryService.saveOrUpdate(userDelivery);
        //改订单状态
        OrderItem orderItem = orderItemService.getOne(new QueryWrapper<OrderItem>().eq("order_num", userDelivery.getOrderNum()));
        Order order = orderService.getById(orderItem.getOrderId());
        order.setOrderStatus(4); //订单已完成
        orderService.saveOrUpdate(order);
        return Result.success();
    }


}
